const sqlite = {
    name:'data',
    path:'_doc/data.db',
    open:function(){
        return new Promise((resolve,reject)=>{
            plus.sqlite.openDatabase({
                name:this.name,
                path:this.path,
                success: (e)=>{
                    resolve()
                },
                fail: (e)=>{
                    console.log(e);
                    resolve(e)
                }
            });
        })
    },
    initDB:async function(tableName){
        try{
            if(plus.sqlite.isOpenDatabase({name:this.name,path:this.path})){
                let boo = await this.createTable(tableName)
                return boo
            }else{
                await this.open()
                let boo = await this.createTable(tableName)
                return boo
            }
        }catch(e){
            console.log(e)
        }
    },
    update:function(sql){
        return new Promise((resolve,reject)=>{
            plus.sqlite.executeSql({
                name: this.name,
                sql: sql,
                success:function(){
                    resolve()
                },
                fail:function(e){
                    console.log(e)
                    reject(e)
                }
            });
        });
    },
    //未完善
    insert:function(tableName,obj){
        return new Promise((resolve,reject)=>{
            plus.sqlite.executeSql({
                name: this.name,
                sql: `insert into ${tableName} values(null,${obj.user_id},${obj.sender_id},${obj.timestamp},'${obj.type}','${JSON.stringify(obj.payload)}','${obj.unread}','${obj.state}')`,
                success:function(res){
                    console.log(res);
                    resolve()
                },
                fail:function(e){
                    console.log(e)
                    reject(e)
                }
            })
        })
    },
    createTable:function(tablename){
        return new Promise((resolve,reject)=>{
            plus.sqlite.executeSql({
                name: this.name,
                sql: [`create table if not exists ${tablename} ("id" INTEGER PRIMARY KEY AUTOINCREMENT,"user_id" INT(8),"sender_id" INT(8),"timestamp" INT(10),"type" char(2),"payload" text,"unread" char(1),"state" char(1))`],
                success: (e)=>{
                    resolve()
                },
                fail(e){ console.log('executeSql failed: '+JSON.stringify(e));reject(e) }
            });
        });
    },
    find:function(sql){
        return new Promise( (resolve, reject)=> {
            plus.sqlite.selectSql({
                name: this.name,
                sql: sql,
                success: function(data){
                    resolve(data)
                },
                fail(e){console.log(e); reject(e)}
            });
        });
    }
}

export {sqlite}